//
//  MineView.swift
//  MyCloset
//
//  Created by 牟好好 on 2024/10/27.
//

import SwiftUI

struct MineView: View {
    var body: some View {
        ScrollView(.vertical, showsIndicators: false) {
            HStack(alignment: .top, spacing: boundsWidth * 0.03) {
                ClothesColumnView(isEvenIndex: true)
                    .frame(maxWidth: boundsWidth * 0.4)
                ClothesColumnView(isEvenIndex: false)
                    .frame(maxWidth: boundsWidth * 0.4)
            }
            .frame(maxWidth: .infinity)
        }
    }
}

struct ClothesColumnView: View {
    var isEvenIndex: Bool
    @ObservedObject var coreVm = CoreDataViewModel.shared
    @StateObject var fileVm = FileManagerViewModel()
    @EnvironmentObject var styleVm: ClothStylesViewModel
    
    var body: some View {
        LazyVStack(spacing: 10) {
            ForEach(coreVm.savedEntities.indices, id: \.self) { index in
                if (index % 2 == 0 && isEvenIndex) || (index % 2 != 0 && !isEvenIndex) {
                    let entity = coreVm.savedEntities[index]
                    if let id = entity.id, let uiImage = fileVm.getImageFromFileManager(id: id) {
                        NavigationLink {
                            ClothesView(id: id, image: uiImage, features: entity.features ?? "")
                                .environmentObject(styleVm)
                        } label: {
                            ClothesCardView(image: uiImage, title: entity.features ?? "") {
                                if let index = coreVm.savedEntities.firstIndex(where: { $0.id == id }) {
                                    coreVm.deleteClothes(indexSet: IndexSet(integer: index))
                                }
                                fileVm.deleteImage(id: id)
                            }
                        }
                    }
                }
            }
            Spacer(minLength: boundsHeight * 0.1 + safeAreaBottom)
        }
    }
}

#Preview {
    NavigationView {
        MineView()
            .environmentObject(ClothStylesViewModel())
    }
}
